package znyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baidubce.qianfan.util.StringUtils;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import znyl.common.exception.base.BaseException;
import znyl.common.utils.UserThreadLocal;
import znyl.framework.web.service.TokenService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;
    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判段该方法是否为Controller方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取请求的token
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)){
            throw new BaseException("token为空");
        }
        //解析token
        Claims claims1 = tokenService.parseToken(token);
        if(ObjectUtil.isNull(claims1)){
            throw new BaseException("token解析失败");
        }

        //获取用户
        Long userId = MapUtil.get(claims1, "userId", Long.class);
        if (ObjectUtil.isNull(userId)){
            throw new BaseException("请先登录");
        }
        UserThreadLocal.set(userId);
        //验证令牌有效期，相差不足20分钟，自动刷新缓存
//        tokenService.verifyToken(tokenService.getLoginUser(request));
        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
